package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.common.util.KeysUtil;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.service.IUserInfoRedisService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void setPhone(String phone, String verifyCode) {
        String key = KeysUtil.VERIFY_CODE.join(phone);
        redisTemplate.opsForValue().set(   key,  verifyCode,
                KeysUtil.VERIFY_CODE.getTime()*60, TimeUnit.SECONDS);
    }

    @Override
    public String getPhone(String phone) {
        String key = KeysUtil.VERIFY_CODE.join(phone);
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public void addToken(String token, UserInfo userInfo) {
        String key = KeysUtil.USER_LOGIN_TOKEN.join(token);
        redisTemplate.opsForValue().set(key, JSON.toJSONString(userInfo),
                KeysUtil.USER_LOGIN_TOKEN.getTime()*60,TimeUnit.SECONDS);
    }

    @Override
    public UserInfo getUserInfoByToken(String token) {
        String key = KeysUtil.USER_LOGIN_TOKEN.join(token);
        redisTemplate.expire(key, KeysUtil.USER_LOGIN_TOKEN.getTime() * 60, TimeUnit.SECONDS);
        return JSON.parseObject(redisTemplate.opsForValue().get(key),UserInfo.class);
    }
}
